<?php

# LemurCMS by Alec Gorge
#
#     This file contains the PHP functions used throught the CMS.
#
# updated: Jan. 12, 2009

class functions {
	public $dbPluginList = false, $db = -10;
	public $activePlugins = array();
	public $adminLoginForm = '
	<form action="" method="post" id="cms-form-login">
		<fieldset>
			<div class="form-row">
				<label for="username">Username: </label><input type="text" name="username" />
			</div>
			<div class="form-row">
				<label for="password">Password: </label><input type="password" name="password" />
			</div>
			<div class="form-row-last">
				<input type="submit" name="login" value="Login" />
			</div>
		</fieldset>
	</form>
	', $sidebar;
	public $interfacePlugins;
	public function __contruct () {
		$this->db_connect();
	}
	public function make_clean_url ($str) {
		return cleanUTF8url($str);
	}
	public function getPluginList () {
		global $dbPluginlistCheck;
		if(empty($dbPluginList)){
			$sql = "SELECT * FROM ".DBTABLEPREFIX."plugins";
			$query = $this->db_query($sql) or die($this->message('error', 'DB Error While Fetching Plugins Error', $this->db->error()));
			while($plugin = $this->db->fetchAssoc($query)) {
				if($plugin['name'] != "" && !array_key_exists($plugin['name'], (array) $this->dbPluginList)) {
					$options = unserialize($plugin['options']);
					$this->dbPluginList[$plugin['name']] = array();
					$this->dbPluginList[$plugin['name']]['options'] = $options;
					if($options['active'] == 'yes' && !in_array($plugin['name'], (array) $this->activePlugins)) {
						$this->activePlugins[] = $plugin['name'];
					}
				}
			}
		}
		return $this->dbPluginlist;
	}
	public function getInterfacePlugins($pluginData) {
		foreach($pluginData as $key => $value) {
			if(array_key_exists('interface', $value))
				$r[] = $value['name'];
		}
		$this->interfacePlugins = $r;
		return $r;
	}
	public function getSidebar () {
		$this->getPluginList();
		if(!is_array($this->sidebar)) {
			$sql = "SELECT * FROM ".DBTABLEPREFIX."sidebar";
			$query = $this->db_query($sql) or die($this->db->error());
			while($row = $this->db->fetchAssoc($query)) {
				if(unserialize($row['data']) && (in_array($row['plugin'], $this->activePlugins || $row['func'] == 'navigation' || $row['func'] == 'secondaryNavigation')))
					$this->sidebar[$row['name']] = array('data' => unserialize($row['data']), 'func' => $row['func']);
				elseif (in_array($row['plugin'], $this->activePlugins) || $row['func'] == 'navigation' || $row['func'] == 'secondaryNavigation')
					$this->sidebar[$row['name']] = array('data' => $row['data'], 'func' => $row['func']);
			}
			return $this->sidebar;
		}
		else {
			return $this->sidebar;
		}
	}
	public function ob_handle_cust_func ($func, $arr = false, $nav = false) {
		ob_start();
			if(is_array($nav) && $func == 'navigation')
				echo navigation(false, false, false, false, false, false, $nav);
			elseif(is_array($nav) && $func == 'secondaryNavigation')
				echo secondaryNavigation(false, false, false, false, false, false, $nav);
			elseif(is_array($arr))
				echo call_user_func_array($func, $arr);
			else
				echo call_user_func($func);
		$output = ob_get_contents();
		ob_end_clean();	
		return $output;
	}
	public function formatSidebar($outBlock, $singleItem, $navFormat, $sNavFormat) {
		global $pluginData;
		$sidebar = $this->getSidebar();
		if(is_array($sidebar)) {
			foreach($sidebar as $key => $value) {
				if(is_callable($value['func'])) {
					$thisItemTitle = $key;
					if($value['func'] == 'navigation')
						$thisItemContent = $this->ob_handle_cust_func($value['func'], false, $navFormat);
					elseif($value['func'] == 'secondaryNavigation')
						$thisItemContent = $this->ob_handle_cust_func($value['func'], false, $sNavFormat);
					elseif(unserialize($value['data']))
						$thisItemContent = $this->ob_handle_cust_func($value['func'], unserialize($value['data']));
					else
						$thisItemContent = $this->ob_handle_cust_func($value['func'], $value['data']);
					$allItems .= sprintf($singleItem, $thisItemTitle, $thisItemContent);
				}
			}
		}
		return sprintf($outBlock, $allItems);
	}
	public function db_connect () {
		$this->db = new DB;
		if(DB_USE == 'mysql') {
			$this->db->host = DBHOST.":".DBPORT;
			$this->db->user = DBUSER;
			$this->db->password = DBPASS;
			$this->db->database = DBNAME;
			$this->db->persistent = true;
		}
		elseif(DB_USE == 'sqlite') {
			$this->db->database = SERVER_ABS_PATH.'includes/db/lemurcms.sqlite3';
		}
		$connect = $this->db->open();
		if(!$connect)
			die('DB Connection Failed. Check config.php');
		//$mysql_con = mysql_connect(DBHOST.":".DBPORT, DBUSER, DBPASS);
		//mysql_select_db(DBNAME, $mysql_con);
	}
	public function db_query($sql) {
		if($this->db == -10)
			$this->db_connect();		
		$result = $this->db->query($sql);	
		return $result;
	}
	public function register_site_info () {
		$sql = "SELECT * FROM ".DBTABLEPREFIX."settings_site";
		$query = $this->db_query($sql) or die($this->db->error());
		while($row = $this->db->fetchArray($query)) {
			$this->page_info['settings'][$row['settingname']]['id'] = stripcslashes(stripcslashes($row['id']));
			$GLOBALS['page_info']['settings'][$row['settingname']]['id'] = stripcslashes(stripcslashes($row['id']));
			$this->page_info['settings'][$row['settingname']]['description'] = stripcslashes(stripcslashes($row['description']));
			$GLOBALS['page_info']['settings'][$row['settingname']]['description'] = stripcslashes(stripcslashes($row['description']));
			$this->page_info['settings'][$row['settingname']]['value'] = stripcslashes(stripcslashes($row['value']));
			$GLOBALS['page_info']['settings'][$row['settingname']]['value'] = stripcslashes(stripcslashes($row['value']));
		}
		define('HOME_PAGE_ID', $this->page_info['settings']['Home Page']['value']);
	}
	public function create_temp_file ($file, $x = 'w', $content) {
		$x = true;
		$file = BASE_URL.'temp/'.$file;
		echo $file;
		$fh = fopen($file, $x) or die(
			$y = "can't open file $file"
		);
		$data = $content;
		fwrite($fh, $data);
		fclose($fh);
		return $y;
	}
	public function deleteFile ($file) {
		if($file != "") {
			unlink(BASE_URL.'temp/'.$path);
			return true;
		}
		else
			return 'can"t open file';
	}
	public function openFile ($path, $relative=1) {
		if($relative == 0) {
			$content = file_get_contents(BASE_URL.$path); 
		}
		else {
			$content = file_get_contents($path); 
		}
	    return mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true)); 
	}
	public function adminLoginForm () {
		return $adminLoginForm;
	}
	public function getSetting($name, $force = false) {
		if(isset($GLOBALS['page_info']['settings'][$name]) && $force == false) {
			return $GLOBALS['page_info']['settings'][$name]['value'];
		}
		else {
			$call_info = array_shift( debug_backtrace() );
			$code_line = $call_info['line'];
			$file = array_pop( explode('/', $call_info['file']));
			$GLOBALS['settingsDebug'] .= "Setting requested (Line $code_line of ".basename($file)."): </strong>$name<br />";
			
			
			//$GLOBALS['settingsDebug'] .= print_r($this->page_info);
			$sql = "SELECT * FROM ".DBTABLEPREFIX."settings_site WHERE settingname = '{$name}'";
			$query = $this->db_query($sql);
			$query = $this->db->fetchAssoc($query);
			$this->page_info['settings'][$name]['value'] = $query['value'];
			return $this->page_info['settings'][$name]['value'];			
		}
	}
	public function prepareSettingArraysSmarty () {
		global $page_settings, $page_settings_system;
		//Remove spaces from settings arrays to be compatible with Smarty Templating System
		foreach($this->page_info['settings'] as $key => $value) {
			$key = str_replace(" ", "_", $key);
			$page_settings[$key] = $value;
		}
	}
	public function validate($if_fail_url="", $if_success_url="") {
		session_start();
		if(!isset($_SESSION['username'])) {
			if($if_fail_url!="") {
				header ("location: ".$if_fail_url."");
				exit();
			}
			return false;
		}
		$username = sanitize_sql_string($_SESSION['username']);
		$qresult = $this->db_query("SELECT * FROM ".DBTABLEPREFIX."users WHERE BINARY username = '".$username."'") or die($this->db->error());
		if ($this->db->numRows($qresult)!="1"){
			if($if_fail_url!="") {
			header ("location: ".$if_fail_url."");
			exit();
			}
			return false;
		}
		$dinfo=$this->db->fetchArray($qresult);
		if ($dinfo['password'] == $_SESSION['password']) {
			if($if_success_url!=="") {
				$this->page_info['user']['value'] = $_SESSION['username'];
				header ("location: ".$if_success_url."");
				exit();
			}
			$this->page_info['user']['value'] = $_SESSION['username'];
			return true;
		}
		else {
			if($if_fail_url!=="") {
				header ("location: ".$if_fail_url."");
				exit();
			}
			return false;
		}		
	}
	public function dump ($str, $var = false) {
		if($var == true) {
			echo '<pre>';
			var_dump($str);
			echo '</pre>';
		}
		else {
			echo '<pre>';
			print_r($str);
			echo '</pre>';
		}
	}
	public function arrayToUl ($inputArray, $withKey = true) {
		$r .= "<ul>";
		foreach($inputArray as $k=>$v) {
			if(is_array($v)) {
				$r .= "<li>$k";
				$this->arrayToUl($v,$withKey);
				$r .= "</li>";
			}
			else {
				if($withKey)
				$r .= "<li>$k : <b>$v</b></li>";
				else
				$r .= "<li>$v</li>";
			}
		}
		$r .= "</ul>";
	}
	/*
		Message Functions
	*/
		public function message($type = 'message', $header = "", $content = "", $small = false) {
			$r .= "<div class='message-wrapper";
			if($small == true) {
				$r .= ' message-small';
			}
			else {
				$r .= ' message-large';
			}
			$r .= "'>";
			switch ($type) {
				case 'message':
					$r .= "<div class='message-message message'>\n\t<div class='message-message-header message-header'>".$header."</div>\n\t<div class='message-message-content message-content'>\n\t\t<p>".$content."</p>\n\t</div>\n</div>";
					break;
				case 'success':
					$r .= "<div class='message-ok message'>\n\t<div class='message-ok-header message-header'>".$header."</div>\n\t<div class='message-ok-content message-content'>\n\t\t<p>".$content."</p>\n\t</div>\n</div>";
					break;
				case 'error':
					$r .= "<div class='message-error message'>\n\t<div class='message-error-header message-header'>".$header."</div>\n\t<div class='message-error-content message-content'>\n\t\t<p>".$content."</p>\n\t</div>\n</div>";
					break;
				case 'warning':
					$r .= "<div class='message-warning message'>\n\t<div class='message-warning-header message-header'>".$header."</div>\n\t<div class='message-warning-content message-content'>\n\t\t<p>".$content."</p>\n\t</div>\n</div>";
					break;
			}
			$r .= "</div>";
			return $r;
		}
}

?>